package com.yuan.pdf;

import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class pdfuntils {
    public static void exportPdfByPdf(String mouldName, Map<String, Object> dataMap, String fileName, HttpServletResponse response) throws Exception {
        ByteArrayOutputStream ba = new ByteArrayOutputStream();
        try {
            PdfReader reader = new PdfReader( "/templates/"+mouldName);

            PdfStamper stamp = new PdfStamper(reader, ba);

            /* 获取模版中的字段 */
            AcroFields form = stamp.getAcroFields();
            /*BaseFont bf = BaseFont.createFont("STSong-Light","gbk" , BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);*/
            BaseFont bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font FontChinese = new Font(bf, 5, Font.NORMAL);
//            form.setSubstitutionFonts(FontChinese);
            form.addSubstitutionFont(bf);
            Map<String, Object> resultMap = dataMap;
            if (resultMap != null) {
                for (String s : resultMap.keySet()) {
                    if (s.equals("checkBoxMap")) {
                        Map<String, String> checkBoxMap = (Map<String, String>) resultMap.get("checkBoxMap");
                        if (checkBoxMap != null) {
                            for (String key : checkBoxMap.keySet()) {
                                System.out.println(key);
                                form.setField(key, "是", "true");
                            }
                        }
                    } else {
                        form.setField(s, (String) resultMap.get(s));
                    }
                }
            }
            stamp.setFormFlattening(true);
            stamp.close();
            reader.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");
        ba.writeTo(response.getOutputStream());
    }



}
